package com.njuse_czf.kg.web.service.impl.handler;


import com.njuse_czf.kg.web.request.GraphQuery;
import com.njuse_czf.kg.web.service.KGGraphService;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class BetterThanHandler extends AbstractQuestionHandler{
    @Override
    public void handleQuestion(QuestionCtx questionCtx, String question, KGGraphService kgGraphService) {
        String regix = "[wW]hich\\s+one\\s+is\\s+better,\\s*(.+?)\\s+or\\s*(.+?)\\?";

        Pattern pattern;
        Matcher matcher;

        GraphQuery query = new GraphQuery();
        query.setDomain(questionCtx.getDomain());
        query.setMatchType(1);
        query.setRelation(new String[]{"better than"});

        //解决第一个问题
        pattern = Pattern.compile(regix);
        matcher = pattern.matcher(question);

        parseRe1(matcher, query, questionCtx, kgGraphService);

        this.getNextHandler().handleQuestion(questionCtx, question, kgGraphService);
    }


    public void parseRe1(Matcher matcher,GraphQuery query, QuestionCtx questionCtx, KGGraphService kgGraphService){
        if(matcher.find()){
            String left = matcher.group(1);
            String right = matcher.group(2);

            //先查询A better than B
            query.setNodeName(left);
            List<HashMap> res = (List<HashMap>) kgGraphService.queryGraphResult(query).get("node");

            //获取结果
            List<String> nodeNames = res.stream()
                    .map(map -> (String) map.get("name"))
                    .collect(Collectors.toList());

            if(nodeNames.contains(right)){
                questionCtx.addAnswer(left + " is better than " + right);
                return;
            }

            //再查询B better than A
            query.setNodeName(right);
            res = (List<HashMap>) kgGraphService.queryGraphResult(query).get("node");
            //获取结果
            nodeNames = res.stream()
                    .map(map -> (String) map.get("name"))
                    .collect(Collectors.toList());

            if(nodeNames.contains(left)){
                questionCtx.addAnswer(right + " is better than " + left);
                return;
            }

            questionCtx.addAnswer("Sorry, I can't answer your question at the current knowledge graph size");
        }
    }
}
